import pymysql
from pycparser.ply.yacc import resultlimit
from pymysql.charset import charset_by_name
from selenium.webdriver.support.ui import WebDriverWait

from Config.config import Mysql


class Base():

    def connect_db(self):
        """
        连接数据库
        :return:
        """
        self.db = pymysql.connect(
            host=str(Mysql['host']),
            user=Mysql['user'],
            port=int(Mysql['port']),
            password=Mysql['password'],
            database=Mysql['database'],
            charset='utf8mb4',  # 添加字符集配置防止乱码
            cursorclass=pymysql.cursors.DictCursor  # 放回字典形式的结果
        )
        return self.db

    def close_db(self):
        """
        关闭数据库
        :return:
        """
        self.db.close()

    def query_db(self, sql):
        """
       执行SQL查询，返回结果
       :param sql: 要执行的SQL语句，如 "SELECT * FROM users"
       :return: 查询结果（列表），失败返回None
        """
        try:
            self.connect_db()#连接数据库
            cursor=self.db.cursor()#获取游标
            cursor.execute(sql)#执行sqsl
            result=cursor.fetchall()#获取所有结果
            return result
        except Exception as e:
            print("数据库查询出错",e)
            return  None
        finally:
            self.close_db()#确保关闭数据库

    def __init__(self, driver):
        self.driver = driver

    def open_url(self, url):
        self.driver.get(url)

    def find_element(self, loc, time_out=20):
        try:
            WebDriverWait(self.driver, time_out, 0.5).until(lambda driver: driver.find_element(*loc).is_displayed())
            return self.driver.find_element(*loc)
        except Exception as e:
            print(e)

    # 点击
    def click(self, loc):
        self.find_element(loc).click()

    # 输入
    def send_keys(self, loc, text):
        self.find_element(loc).send_keys(text)

    # 滑动到底部
    def dibu(self):
        self.driver.execute_script('window.scrollTo(0,document.body.scrollHeight)')
